package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.dao.SeckillOrderMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.pojo.seckill.SeckillStatus;
import com.qingcheng.service.seckill.SeckillOrderService;
import com.qingcheng.task.MultiThreadingCreateOrder;
import com.qingcheng.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private MultiThreadingCreateOrder multiThreadingCreateOrder;
    @Autowired
    private RedisTemplate redisTemplate;

    /****
     * 添加订单
     * @param id
     * @param time
     * @param username
     */
    @Override
    public Boolean add(Long id, String time, String username) {
        //利用REDIS的单线程和自增方法保证每个用户只能抢一次单
        Long userQueueCount = redisTemplate.boundHashOps("UserQueueCount").increment(username, 1);
        if (userQueueCount>1){
            //100错误：重复抢单
            throw new RuntimeException("100");
        }

        //创建队列所需对象  存入所需信息
        SeckillStatus seckillStatus = new SeckillStatus(username,new Date(),1, id, time);

        //存入redis队列中
        //要左存右取
        redisTemplate.boundListOps("SeckillStatus").leftPush(seckillStatus);
        //存入排队信息
        redisTemplate.boundListOps("SeckillOrderQueue").leftPush(seckillStatus);

        //存入抢单状态信息，方便查询是否已下单成功
        redisTemplate.boundHashOps("UserQueueStatus").put(username,seckillStatus);
        //异步调用秒杀抢单测试
        multiThreadingCreateOrder.createOrder();
        return false;

    }
    /**
     * 查询订单状态是否已支付
     * @param username
     * @return
     */
    @Override
    public SeckillStatus queryStatus(String username) {
        return (SeckillStatus) redisTemplate.boundHashOps("UserQueueStatus").get(username);


    }

    @Override
    public List<SeckillOrder> querySeckillOrderListByUsername(String username) {
        Example example=new Example(SeckillOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",username);
        List<SeckillOrder> seckillOrders = seckillOrderMapper.selectByExample(example);
        return seckillOrders;
    }
}

